﻿/*
 * 描述：该例子通过开启10个线程，每个线程执行withdraw方法100次来展示了线程锁的作用，线程锁的作用
 *       是确保某个方法在多线程环境下，在同一时间只有一个线程可以执行该函数
 */
using System;
using System.Threading;

namespace IceDog.Lib.IceDogLock
{
    public class Count
    {
        private static readonly object Lock = new Object();//锁对象
        private int _num;
        private readonly Random _random;

        public Count(int num)
        {
            _num = num;
            _random = new Random();
        }

        /// <summary>
        /// 输出一个计算结果
        /// </summary>
        /// <param name="amount">传入 _num 要减去的值</param>
        /// <returns></returns>
        private int WithDraw(int amount)
        {
            if (_num < 0)
            {
                Console.WriteLine(_num);
                throw new Exception("负值");
            }
            lock (Lock)
            {
                if (_num >= amount)
                {
                    Console.WriteLine("--------------------------------");
                    Console.WriteLine("num执行WithDraw方法前：" +
                        _num);
                    Console.WriteLine("要减去的数值amount：" + amount);
                    _num -= amount;
                    Console.WriteLine("num执行WithDraw方法后：" + _num);
                    Console.WriteLine("++++++++++++++++++++++++++++++++");
                    return amount;
                }
                return 0;
            }
        }
        /// <summary>
        /// 把WithDraw方法执行100次
        /// </summary>
        public void DoTransactions()
        {
            for (int i = 0; i < 100; i++)
            {
                WithDraw(_random.Next(1, 100));
            }
        }
    }
}
